package cn.edu.ccut.refactor;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;

import cn.edu.ccut.util.RefactorXMLParse;

/**
 * 
 * @author Bai Yucheng 2008-4-16
 * 
 */
public class RenameSaturnFileProcessor extends AbstractRenameProcessor {

	private IFile saturnFile;
	private String fNewElementName;
	private IStructuredSelection selection;
	public RenameSaturnFileProcessor(IFile file, IStructuredSelection selection) {
		saturnFile = file;
		this.selection = selection ;
		if (saturnFile != null)
			setNewElementName(saturnFile.getName());
	}

	private boolean hasFileExtention(String s) {
		int i = s.lastIndexOf('.');
		return i != -1;
	}

	private String getFullElementName(String s) {
		if (hasFileExtention(s))
			return s;
		else
			return s + "." + getFileExtention(); 
	}
	
	private String getSimpleName(String s) {
		if (hasFileExtention(s)) {
			return s.substring(0, s.lastIndexOf(".")); 
		} else {
			return s;
		}
	}

	public void setNewElementName(String s) {
		Assert.isNotNull(s);
		fNewElementName = s;
	}

	public String getNewElementName() {
		return fNewElementName;
	}

	public String getCurrentElementName() {
		return saturnFile.getName();
	}

	public Object getNewElement() throws CoreException {
		return ResourcesPlugin.getWorkspace().getRoot().findMember(
				createNewPath(getNewElementName()));
	}

	public RefactoringStatus checkNewElementName(String s) throws CoreException {
		Assert.isNotNull(s, "new name"); 
		IContainer icontainer = saturnFile.getParent();
		if (s.equals(getCurrentElementName()))
			return RefactoringStatus.createFatalErrorStatus(""); 
		if (icontainer == null)
			return RefactoringStatus.createFatalErrorStatus(""); 
		s = getFullElementName(s);
		if (icontainer.findMember(s) != null)
			return RefactoringStatus.createFatalErrorStatus(""); 
		if (!icontainer.getFullPath().isValidSegment(s))
			return RefactoringStatus.createFatalErrorStatus(""); 
		RefactoringStatus refactoringstatus = RefactoringStatus
				.create(icontainer.getWorkspace().validateName(s,
						saturnFile.getType()));
		if (!refactoringstatus.hasFatalError())
			refactoringstatus.merge(RefactoringStatus.create(icontainer
					.getWorkspace().validatePath(createNewPath(s),
							saturnFile.getType())));
		return refactoringstatus;
	}

	public Change createChange(IProgressMonitor iprogressmonitor)
			throws CoreException, OperationCanceledException {
		iprogressmonitor.beginTask("", 1); 
		CompositeChange compositechange1;
		IProject iproject = saturnFile.getProject();
		String projectName = iproject.getName();
		try {
			String s = saturnFile.getName();
			String s1 = ""; 
			CompositeChange compositechange = new CompositeChange(s1);
			if (isUpdateReference()) {
				String key = null;
				String key2 = null;
				String newKey = null;
				String newKey2 = null;
				String prefix = null;
				String suffix = null;
				String dataName = null;
				String parentName = null;
				String pkgName = null;
				IResource parentFolder = null;
//				
				key = RefactorXMLParse.getKeyValue(saturnFile);
				
				if (saturnFile.getFileExtension().equals("saturndata")) {
					key2 = "namespace=" + '"' + key.split("::")[0] + '"'
					+ " saturnDataType=" + '"' + key.split("::")[1] + '"';
					prefix = key2.substring(0, key2.indexOf(projectName) + projectName.length() + 1);
					suffix = '"' + " saturnDataType="; 
					dataName = key2.substring(key2.lastIndexOf("=") + 1); 
				}
				int flag = 0;
				if(isMoveFile()) {
					
					parentFolder = getDestFolder().getParent();
					parentName = parentFolder.getName();
					pkgName = getDestFolder().getName();
					projectName = saturnFile.getProject().getName();
					if (parentName.endsWith("module") || parentName.endsWith("Module")) {  
						if (saturnFile.getFileExtension().equals("saturndata")) {  
							newKey = key.substring(0, key.indexOf(projectName) + projectName.length()) + "/" + parentName + "/" + pkgName + "::" + getSimpleName(s);   
							newKey2 = prefix + parentName + "/" + pkgName + suffix + dataName; 
						} else if (saturnFile.getFileExtension().equals("jsp")) { 
							newKey = "/" + projectName + "/" + parentName + "/" + pkgName + "/" + s;    
						} else if (saturnFile.getFileExtension().endsWith("wf")) {
							newKey = projectName + ":://" + parentName + "/" +  pkgName + "/" + s;  
						}
						else {
							newKey = "/" + parentName + "/" + pkgName + "/" + s;   
						}		
					} else {
						if (saturnFile.getFileExtension().equals("saturndata")) {  
							newKey = key.substring(0, key.lastIndexOf("/")) + "/" + pkgName + "::" + getSimpleName(s);   
							newKey2 = prefix + pkgName + suffix + dataName;
						} else if (saturnFile.getFileExtension().equals("jsp")) { 
				            newKey = "/" + projectName + "/" + pkgName + "/" + s;   
						} else if (saturnFile.getFileExtension().equals("wf")) { 
							newKey = projectName + ":://"  + pkgName + "/" + s;  
						} else {
							newKey = "/" + pkgName + "/" + s;  
						}	
					}
					flag = 1;
                } else {     	
    				if (saturnFile.getFileExtension().equals("saturndata")) {   
    					int i = key.indexOf(getSimpleName(s));
        				String s4 = key.substring(0, i);
    					newKey = s4 + getSimpleName(getNewElementName());
    					newKey2 = key2.substring(0, key2.lastIndexOf("=") + 1) + '"' + getSimpleName(getNewElementName()) + '"'; 
    				} else {
    					newKey = getNewKey() + getFullElementName(getNewElementName());
    				}		
                }
				
				if (saturnFile.getFileExtension().equals("saturndata")) {  
					SearchEngine searchengine2 = new SearchEngine(iproject, key2, newKey2, flag);
					Change achange2[] = searchengine2.search(iprogressmonitor);
					compositechange.addAll(achange2);
				} else if (saturnFile.getFileExtension().equals("jsp")) {
					SearchEngine searchengine2 = new SearchEngine(iproject, key, newKey, flag);
					Change achange2[] = searchengine2.search(iprogressmonitor);
					compositechange.addAll(achange2);
				} else{
					SearchEngine searchengine1 = new SearchEngine(iproject, key, newKey, flag);
					Change achange1[] = searchengine1.search(iprogressmonitor);
					compositechange.addAll(achange1);
				}
			}
			if (isMoveFile()) {
				compositechange.add(new MoveSaturnFileChange(saturnFile, getDestFolder()));
			} else {
				compositechange.add(new RenameSaturnFileChange(saturnFile, getNewFileName()));	
			}		
			compositechange1 = compositechange;
		} finally {
			iprogressmonitor.done();
		}
		return compositechange1;
	}

	public String getNewFileName() {
		if (hasFileExtention(getNewElementName()))
			return getNewElementName();
		else
			return getNewElementName() + "." + getFileExtention(); 
	}

	public String getFileExtention() {
		return saturnFile.getFileExtension();
	}

	private String createNewPath(String s) {
		return saturnFile.getFullPath().removeLastSegments(1).append(s).toString();
	}

	public Object[] getElements() {
		return (new Object[] { saturnFile });
	}

	public IFile getSaturnFile() {
		return saturnFile;
	}

	public void setSaturnFile(IFile saturnFile) {
		this.saturnFile = saturnFile;
	}
	/**
	 * 复制后，重新命名，改变key的值为当前文件夹。
	 * @author alf 2008-8-13
	 */
	private String getNewKey() {
		if(selection.getFirstElement() instanceof IFile){
			
			String s = saturnFile.getName();
			String filePath = ((IFile) selection.getFirstElement()).getParent().getFullPath().toString();
			String projectPath = ((IFile) selection.getFirstElement()).getProject().getFullPath().toString()+ "/" + "src" + "/";
			int i = filePath.indexOf(projectPath);
			String key = filePath.substring(i + projectPath.length());
			String projectName = saturnFile.getProject().getName();
			
			if (s.endsWith(".wf")) {
				return projectName + ":://" + key + "/";
			}else if (s.endsWith(".jsp")){
				return "/" + projectName + "/" + key + "/";
			} else{
				return "/" + key + "/";
			}
		}
		return null;
	}

}
